import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
import 'package:charset_converter/charset_converter.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:shen_nai/app/user_controller.dart';
import 'package:shen_nai/entity/device_entity.dart';
import 'package:shen_nai/eventbus/event_bus.dart';
import 'package:shen_nai/routes/app_routes.dart';
import 'package:shen_nai/socket/socket_server_manage.dart';

/**
 * 数据界面
 */
class DataPage extends StatefulWidget {
  const DataPage({Key? key}) : super(key: key);

  @override
  State<DataPage> createState() => _DataPageState();
}

class _DataPageState extends State<DataPage> with TickerProviderStateMixin {
  final List<String> _controlList = [];

  final List<String> _selectList = [];

  DeviceEntity? _deviceEntity;
  //选择的模拟量1
  String _show1 = '';
  //选择的模拟量1的值
  String _value1 = '0';
  //第一个表动画
  late AnimationController _controller1;
  late Animation<double> _animation1;

  //选择的模拟量2
  String _show2 = '';
  //选择的模拟量1的值
  String _value2 = '0';
  //第二个表动画
  late AnimationController _controller2;
  late Animation<double> _animation2;
  //实时数据监听
  StreamSubscription? _subscription;

  double currentPointer = -1 / 12 * 2;
  //指针1位置
  double pointer1 = -1 / 12 * 2;

  //指针2位置
  double pointer2 = -1 / 12 * 2;

  double dishWidth = 0;

  double dish_10000 = 12000;
  double dish_120 = 144;

  //检修信息
  List<String> serviceList = [];
  List<String> infomationNameList = [
    '电源柜',
    '炉体',
    '水冷系统',
    '水冷电缆',
    '感应圈',
    '油路系统',
    '可控硅',
    '电容',
    '部件1',
    '部件2'
  ];

  List<String> remarkList = [
    '每月对电柜内部电气接点螺丝，线路，水路进行常规检查发现有故障隐患的及时处理。',
    '每月做炉体的全面检查有故障隐患的及时排除。',
    '三个月内进行风冷系统全面检查及冷却管水垢的清理。',
    '半年至一年把水电缆拆开看看内部是否有局部断线及接触不良现象。',
    '半年至一年要检查感应圈通水是否顺畅，每组水路出水端开放看是否有水嘴腐蚀及不同程度的堵塞现象。',
    '半年至一年要检查油站是否有缺油渗油现象。',
    '假如连续更换可控硅就要检查相关阻容保护是否有问题，水套是否不平整，原则上有连续四次以上更换可控硅就要连带更换水套。',
    '半年至一年检查水嘴是否有电解及腐蚀氧化物堵路。',
    '无',
    '无'
  ];

  @override
  void initState() {
    super.initState();
    // 强制横屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    _deviceEntity = Get.arguments;
    //WebSocketManage().subscription(_deviceEntity!.number!);

    _controller1 = AnimationController(
        duration: const Duration(milliseconds: 300), vsync: this)
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          //controller.reverse();
        } else if (status == AnimationStatus.dismissed) {
          //controller.forward();
        }
      });

    _controller2 = AnimationController(
        duration: const Duration(milliseconds: 300), vsync: this)
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          //controller.reverse();
        } else if (status == AnimationStatus.dismissed) {
          //controller.forward();
        }
      });

    _animation1 = Tween<double>(begin: currentPointer, end: currentPointer)
        .animate(_controller1);
    _animation2 = Tween<double>(begin: currentPointer, end: currentPointer)
        .animate(_controller2);
    _controller1.forward();
    _controller2.forward();

    _getControllData(_deviceEntity!.ID.toString());

    _subscription = eventBus.on<EquipmentInformationEvent>().listen((event) {
      log(event.data.serialNumber!);
      if (_deviceEntity!.number == event.data.serialNumber!) {
        //_deviceEntity!.isOnline = true;

        //_subscription?.cancel();
        List<int> list = [];
        list.addAll(event.data.bit14List!);
        list.addAll(event.data.bit7List!);
        int index1 = _controlList.indexWhere((element) => element == _show1);
        if (index1 != -1) {
          int value1 = list[index1];
          //log(value1.toString());
          double currentValue1;
          if (_show1.contains('温度')) {
            currentValue1 = (value1.toDouble() / dish_120) + currentPointer;
          } else {
            currentValue1 = (value1.toDouble() / dish_10000) + currentPointer;
          }

          if (currentValue1 != pointer1) {
            setState(() {
              _animation1 = Tween<double>(begin: pointer1, end: currentValue1)
                  .animate(_controller1);
              _controller1.reset();
              _controller1.forward();
              pointer1 = currentValue1;
              _value1 = value1.toString();
            });
          }
        }

        int index2 = _controlList.indexWhere((element) => element == _show2);
        if (index2 != -1) {
          int value2 = list[index2];
          //log(value1.toString());
          double currentValue2;
          if (_show2.contains('温度')) {
            currentValue2 = (value2.toDouble() / dish_120) + currentPointer;
          } else {
            currentValue2 = (value2.toDouble() / dish_10000) + currentPointer;
          }
          if (currentValue2 != pointer2) {
            setState(() {
              _animation2 = Tween<double>(begin: pointer2, end: currentValue2)
                  .animate(_controller2);
              _controller2.reset();
              _controller2.forward();
              pointer2 = currentValue2;
              _value2 = value2.toString();
            });
          }
          setState(() {
            _deviceEntity!.power1 = event.data.aPower;
            _deviceEntity!.time1 = event.data.aTime;
            _deviceEntity!.power2 = event.data.bPower;
            _deviceEntity!.time2 = event.data.bTime;
          });
        }
      }
    });
  }

  @override
  void dispose() {
    // 强制竖屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
    _subscription?.cancel();
    _subscription?.cancel();
    _controller1.dispose();
    _controller2.dispose();
    super.dispose();
  }

  //获取模拟量和开关量
  _getControllData(String id) {
    List<int> firstList = [];
    SocketServerManage().writeData('query Bit14 $id', (data) async {
      var value = String.fromCharCodes(data);
      firstList.addAll(data);
      if (value.contains('over')) {
        var data = Uint8List.fromList(firstList);
        int length = int.parse(
            String.fromCharCodes(data).substring(0, 16).split(' ')[2]);
        String value =
            await CharsetConverter.decode('GBK', data.sublist(16, 16 + length));

        _controlList.addAll(value.split(' '));
        _controlList.removeLast();
        firstList.clear();
        SocketServerManage().writeData('query Bit7 $id', (data) async {
          firstList.addAll(data);
          var value = String.fromCharCodes(data);
          if (value.contains('over')) {
            var data = Uint8List.fromList(firstList);
            int length = int.parse(
                String.fromCharCodes(data).substring(0, 16).split(' ')[2]);
            String value = await CharsetConverter.decode(
                'GBK', data.sublist(16, 16 + length));
            log(value);
            _controlList.addAll(value.split(' '));

            _controlList.removeLast();
            firstList.clear();
            Get.find<UserController>().setBit100List(_controlList);
            _selectList
                .addAll(_controlList.where((element) => element != 'NULL'));
            setState(() {
              _show1 = _selectList[0];
              _show2 = _selectList[1];
            });
            log(_controlList.toString() + _controlList.length.toString());
            SocketServerManage().writeData('query Bit1 $id', (data) async {
              firstList.addAll(data);
              var value = String.fromCharCodes(data);
              //log(value);
              if (value.contains('over')) {
                var data = Uint8List.fromList(firstList);
                int length = int.parse(
                    String.fromCharCodes(data).substring(0, 16).split(' ')[2]);
                String value = await CharsetConverter.decode(
                    'GBK', data.sublist(16, 16 + length));

                var split = value.split(' ');
                split.removeLast();
                firstList.clear();
                log(split.length.toString());
                Get.find<UserController>().setBit140List(split);
              }
            });
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    dishWidth = MediaQuery.of(context).size.height -
        MediaQuery.of(context).padding.top -
        135;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        centerTitle: false,
        titleSpacing: 0,
        title: Text(
          _deviceEntity!.name ?? '',
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: const TextStyle(color: Colors.white, fontSize: 12),
        ),
        actions: [
          Row(
            children: [
              InkWell(
                onTap: () => {
                  if (Get.find<UserController>().jurisdiction == 10)
                    {_showUpdateMoneyDialog()}
                },
                child: Row(children: [
                  const Text(
                    '质保金：',
                    style: TextStyle(color: Colors.white, fontSize: 12),
                  ),
                  Text(
                    _deviceEntity!.qualityIsBuy == 0 ? '未付' : '已付',
                    style: TextStyle(
                        color: _deviceEntity!.qualityIsBuy == 0
                            ? Colors.red
                            : Colors.green,
                        fontSize: 12),
                  ),
                  const SizedBox(
                    width: 5,
                  ),
                  Image.asset(
                    'assets/images/down.png',
                    width: 12,
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  const Text(
                    '质保期：',
                    style: TextStyle(color: Colors.white, fontSize: 12),
                  ),
                  Text(
                    _deviceEntity!.qualityIsBuy == 0
                        ? '${_deviceEntity!.qualityDays}天'
                        : '完成',
                    style: TextStyle(
                        color: _deviceEntity!.qualityIsBuy == 0
                            ? Colors.red
                            : Colors.green,
                        fontSize: 12),
                  ),
                  const SizedBox(
                    width: 5,
                  ),
                  Image.asset(
                    'assets/images/down.png',
                    width: 12,
                  ),
                  SizedBox(
                    width:
                        Get.find<UserController>().jurisdiction == 0 ? 10 : 5,
                  )
                ]),
              ),
              Get.find<UserController>().jurisdiction != 2
                  ? ElevatedButton(
                      onPressed: () {
                        Get.toNamed(AppRoute.REAL_DATA,
                            arguments: _deviceEntity);
                      },
                      child: const Text(
                        '实时数据',
                        style: TextStyle(fontSize: 12),
                      ),
                      style: ElevatedButton.styleFrom(
                          primary: const Color(0xff3486F7),
                          minimumSize: const Size(0, 0),
                          padding: const EdgeInsets.symmetric(
                              vertical: 4, horizontal: 8)),
                    )
                  : const SizedBox(),
              const SizedBox(
                width: 5,
              ),
              ElevatedButton(
                onPressed: () {
                  _deviceEntity!.itemType = 0;
                  Get.toNamed(AppRoute.LINE_CHART_DETAIL,
                      arguments: _deviceEntity);
                },
                child: const Text(
                  '实时曲线',
                  style: TextStyle(fontSize: 12),
                ),
                style: ElevatedButton.styleFrom(
                    primary: const Color(0xff3486F7),
                    minimumSize: const Size(0, 0),
                    padding:
                        const EdgeInsets.symmetric(vertical: 4, horizontal: 8)),
              ),
              const SizedBox(
                width: 5,
              ),
              ElevatedButton(
                onPressed: () {
                  _deviceEntity!.itemType = 1;
                  Get.toNamed(AppRoute.LINE_CHART_DETAIL,
                      arguments: _deviceEntity);
                },
                child: const Text('前90分钟', style: TextStyle(fontSize: 12)),
                style: ElevatedButton.styleFrom(
                    primary: const Color(0xffEE6D61),
                    minimumSize: const Size(0, 0),
                    padding:
                        const EdgeInsets.symmetric(vertical: 4, horizontal: 8)),
              ),
              const SizedBox(
                width: 5,
              ),
              ElevatedButton(
                onPressed: () {
                  _deviceEntity!.itemType = 2;
                  Get.toNamed(AppRoute.LINE_CHART_DETAIL,
                      arguments: _deviceEntity);
                },
                child: const Text('历史曲线', style: TextStyle(fontSize: 12)),
                style: ElevatedButton.styleFrom(
                    primary: const Color(0xffEE6D61),
                    minimumSize: const Size(0, 0),
                    padding:
                        const EdgeInsets.symmetric(vertical: 4, horizontal: 8)),
              ),
            ],
          )
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              width: double.infinity,
              height: 1,
              color: const Color(0xffF3F3F3),
              margin: const EdgeInsets.symmetric(horizontal: 16),
            ),
            const SizedBox(
              height: 5,
            ),
            Row(
              children: [
                const SizedBox(
                  width: 20,
                ),
                Expanded(
                    child: Container(
                  height: 28,
                  decoration: BoxDecoration(
                      color: const Color(0xff1E314D),
                      borderRadius: BorderRadius.circular(6)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Text(
                        'A累计时间',
                        style: TextStyle(color: Colors.white),
                      ),
                      const SizedBox(
                        width: 5,
                      ),
                      Text(
                        _deviceEntity!.time1.toString(),
                        style: const TextStyle(
                            color: Color(0xff3486F7),
                            fontFamily: 'ShuMaGuan',
                            fontSize: 22),
                      ),
                      const SizedBox(
                        width: 16,
                      ),
                      const Text(
                        'A累计电量',
                        style: TextStyle(color: Colors.white),
                      ),
                      const SizedBox(
                        width: 5,
                      ),
                      Text(
                        _deviceEntity!.power1.toString(),
                        style: const TextStyle(
                            color: Color(0xff3486F7),
                            fontFamily: 'ShuMaGuan',
                            fontSize: 22),
                      ),
                    ],
                  ),
                )),
                const SizedBox(
                  width: 30,
                ),
                Expanded(
                    child: Container(
                  height: 28,
                  decoration: BoxDecoration(
                      color: const Color(0xff1E314D),
                      borderRadius: BorderRadius.circular(6)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Text(
                        'B累计时间',
                        style: TextStyle(color: Colors.white),
                      ),
                      const SizedBox(
                        width: 5,
                      ),
                      Text(
                        _deviceEntity!.time2.toString(),
                        style: const TextStyle(
                            color: Color(0xff3486F7),
                            fontFamily: 'ShuMaGuan',
                            fontSize: 22),
                      ),
                      const SizedBox(
                        width: 16,
                      ),
                      const Text(
                        'B累计电量',
                        style: TextStyle(color: Colors.white),
                      ),
                      const SizedBox(
                        width: 5,
                      ),
                      Text(
                        _deviceEntity!.power2.toString(),
                        style: const TextStyle(
                            color: Color(0xff3486F7),
                            fontFamily: 'ShuMaGuan',
                            fontSize: 22),
                      ),
                    ],
                  ),
                )),
                const SizedBox(
                  width: 20,
                )
              ],
            ),
            //转盘
            Stack(
              children: [
                SizedBox(
                  width: double.infinity,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Column(
                        children: [
                          SizedBox(
                            width: dishWidth,
                            height: dishWidth,
                            child: Stack(
                              alignment: Alignment.center,
                              children: [
                                Image.asset(
                                  _show1.contains('温度')
                                      ? 'assets/images/dish_120.png'
                                      : 'assets/images/dish_10000.png',
                                  fit: BoxFit.cover,
                                ),
                                Positioned(
                                    left: 0,
                                    right: 0,
                                    top: 0,
                                    bottom: 0,
                                    child: RotationTransition(
                                      turns: _animation1,
                                      child: Image.asset(
                                        'assets/images/circle_pointer.png',
                                        fit: BoxFit.cover,
                                      ),
                                    )),
                                Positioned(
                                    child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      _value1,
                                      style: const TextStyle(
                                          color: Color(0xff00A7FE),
                                          fontSize: 16,
                                          fontWeight: FontWeight.bold,
                                          fontFamily: 'ShuMaGuan'),
                                    ),
                                    Text(
                                      getUnitText(_show1),
                                      style: const TextStyle(
                                          color: Color(0xff00A7FE),
                                          fontSize: 14),
                                    )
                                  ],
                                ))
                              ],
                            ),
                          ),
                          InkWell(
                            onTap: () {
                              _showDialog(1);
                            },
                            child: Container(
                              height: 26,
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 12),
                              decoration: BoxDecoration(
                                  border: Border.all(
                                    color: const Color(0xff3486F7),
                                    width: 1,
                                  ),
                                  borderRadius: BorderRadius.circular(5)),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    _show1,
                                    style: const TextStyle(
                                        color: Colors.white, fontSize: 12),
                                  ),
                                  const SizedBox(
                                    width: 5,
                                  ),
                                  Image.asset(
                                    'assets/images/down.png',
                                    width: 12,
                                  )
                                ],
                              ),
                            ),
                          )
                        ],
                      ),
                      InkWell(
                        onTap: () {
                          if (serviceList.isEmpty) {
                            List<int> list = [];
                            SocketServerManage().writeData(
                                'query devtime ${_deviceEntity!.ID.toString()}',
                                (Uint8List value) {
                              list.addAll(value);
                              if (String.fromCharCodes(value)
                                  .contains('over')) {
                                List<String> split =
                                    String.fromCharCodes(list.sublist(0, 16))
                                        .split(' ');
                                serviceList = String.fromCharCodes(list.sublist(
                                        16,
                                        16 +
                                            int.parse(split[split.length - 1])))
                                    .split(' ');
                                _showServiceDialog(serviceList);
                              }
                            });
                          } else {
                            _showServiceDialog(serviceList);
                          }
                        },
                        child: Container(
                          margin: const EdgeInsets.only(
                              top: 22, left: 27, right: 27),
                          child: Row(
                            children: [
                              const Text('检修信息',
                                  style: TextStyle(
                                      color: Color(0xffFAB909), fontSize: 12)),
                              const SizedBox(
                                width: 5,
                              ),
                              Image.asset(
                                'assets/images/down.png',
                                width: 12,
                              )
                            ],
                          ),
                        ),
                      ),
                      Column(
                        children: [
                          SizedBox(
                            width: dishWidth,
                            height: dishWidth,
                            child: Stack(
                              alignment: Alignment.center,
                              children: [
                                Image.asset(
                                  _show2.contains('温度')
                                      ? 'assets/images/dish_120.png'
                                      : 'assets/images/dish_10000.png',
                                  fit: BoxFit.cover,
                                ),
                                Positioned(
                                    left: 0,
                                    right: 0,
                                    top: 0,
                                    bottom: 0,
                                    child: RotationTransition(
                                      turns: _animation2,
                                      child: Image.asset(
                                        'assets/images/circle_pointer.png',
                                        fit: BoxFit.cover,
                                      ),
                                    )),
                                Positioned(
                                    child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      _value2,
                                      style: const TextStyle(
                                          color: Color(0xff00A7FE),
                                          fontSize: 16,
                                          fontWeight: FontWeight.bold,
                                          fontFamily: 'ShuMaGuan'),
                                    ),
                                    Text(
                                      getUnitText(_show2),
                                      style: const TextStyle(
                                          color: Color(0xff00A7FE),
                                          fontSize: 12),
                                    )
                                  ],
                                ))
                              ],
                            ),
                          ),
                          InkWell(
                            onTap: () {
                              _showDialog(2);
                            },
                            child: Container(
                              height: 26,
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 12),
                              decoration: BoxDecoration(
                                  border: Border.all(
                                    color: const Color(0xff3486F7),
                                    width: 1,
                                  ),
                                  borderRadius: BorderRadius.circular(5)),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    _show2,
                                    style: const TextStyle(
                                        color: Colors.white, fontSize: 12),
                                  ),
                                  const SizedBox(
                                    width: 5,
                                  ),
                                  Image.asset(
                                    'assets/images/down.png',
                                    width: 12,
                                  )
                                ],
                              ),
                            ),
                          )
                        ],
                      )
                    ],
                  ),
                ),
                Positioned(
                    bottom: 10,
                    right: 26,
                    child: InkWell(
                      onTap: () {
                        exit(0);
                      },
                      child: Image.asset(
                        'assets/images/exit.png',
                        width: 26,
                      ),
                    ))
              ],
            ),
          ],
        ),
      ),
    );
  }

  //1.第一个轮盘 2.第二个轮盘
  void _showDialog(int type) {
    String value = type == 1 ? _show1 : _show2;
    Get.bottomSheet(
        SafeArea(
          child: SizedBox(
            //color: Colors.white,
            height: 240,
            child: Column(
              children: [
                Row(
                  children: [
                    TextButton(
                        onPressed: () {
                          Get.back();
                        },
                        child: const Text(
                          '取消',
                          style: TextStyle(color: Colors.blue, fontSize: 16),
                        )),
                    const Expanded(
                        child: Text(
                      '请选择',
                      style: TextStyle(fontSize: 16),
                      textAlign: TextAlign.center,
                    )),
                    TextButton(
                        onPressed: () {
                          setState(() {
                            if (type == 1) {
                              _show1 = value;
                            } else {
                              _show2 = value;
                            }
                          });
                          Get.back();
                        },
                        child: const Text(
                          '确定',
                          style: TextStyle(color: Colors.blue, fontSize: 16),
                        ))
                  ],
                ),
                Expanded(
                    child: CupertinoPicker(
                  itemExtent: 40,
                  onSelectedItemChanged: (index) {
                    value = _selectList[index];
                  },
                  children: _selectList.map((data) {
                    return Center(
                      child: Text(data),
                    );
                  }).toList(),
                ))
              ],
            ),
          ),
        ),
        backgroundColor: Colors.white,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(15))));
  }

  //修改保证金dialog
  _showUpdateMoneyDialog() {
    int _selectIndexMoney = 0;
    Get.bottomSheet(
        SafeArea(
          child: SizedBox(
            //color: Colors.white,
            height: 240,
            child: Column(
              children: [
                Row(
                  children: [
                    TextButton(
                        onPressed: () {
                          Get.back();
                        },
                        child: const Text(
                          '取消',
                          style: TextStyle(color: Colors.blue, fontSize: 16),
                        )),
                    const Expanded(
                        child: Text(
                      '请选择质保金是否已付',
                      style: TextStyle(fontSize: 16),
                      textAlign: TextAlign.center,
                    )),
                    TextButton(
                        onPressed: () {
                          Get.back();
                          _showSelectDateDialog(_selectIndexMoney);
                        },
                        child: const Text(
                          '确定',
                          style: TextStyle(color: Colors.blue, fontSize: 16),
                        ))
                  ],
                ),
                Expanded(
                    child: CupertinoPicker(
                  itemExtent: 40,
                  onSelectedItemChanged: (index) {
                    _selectIndexMoney = index;
                  },
                  children: ['未付', '已付'].map((data) {
                    return Center(
                      child: Text(data),
                    );
                  }).toList(),
                ))
              ],
            ),
          ),
        ),
        backgroundColor: Colors.white,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(15))));
  }

  //选择质保日期
  _showSelectDateDialog(int selectMoney) async {
    DateTime? date = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2022),
      lastDate: DateTime(2100),
      helpText: '请选择保证金日期',
      cancelText: '取消',
      confirmText: '确认',
    );
    if (date != null) {
      String time = formatDate(date, [yyyy, '-', mm, '-', dd]);
      _modifyQualityGuarantee(time, selectMoney, date);
    }
  }

  //修改质保
  _modifyQualityGuarantee(String date, int select, DateTime dateTime) {
    log('modify device $date ${select.toString()} ${_deviceEntity!.ID.toString()}');
    SocketServerManage().writeData(
        'modify device $date ${select.toString()} ${_deviceEntity!.ID.toString()}',
        (value) {
      log(String.fromCharCodes(value));
      if (String.fromCharCodes(value).contains('suce')) {
        EasyLoading.showToast('修改成功');
        _deviceEntity?.qualityIsBuy = select;
        _deviceEntity?.qualityDate = date;
        _deviceEntity?.qualityDays =
            dateTime.difference(DateTime.now()).inDays.toString();
        setState(() {
          _deviceEntity;
        });
        eventBus.fire(UpdateQualityGuaranteeSuccess(_deviceEntity!));
      } else {
        EasyLoading.showToast('修改失败');
      }
    });
  }

  //检修信息dialog
  _showServiceDialog(List<String> list) {
    Get.defaultDialog(
      title: '检修信息',
      //titleStyle: TextStyle()
      content: Column(
        //crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _getDialogContentView(
            infomationNameList[0],
            list[0],
            remarkList[0],
            _deviceEntity!.service1.toString(),
            infomationNameList[1],
            list[1],
            remarkList[1],
            _deviceEntity!.service2.toString(),
            infomationNameList[2],
            list[2],
            remarkList[2],
            _deviceEntity!.service3.toString(),
            infomationNameList[3],
            list[3],
            remarkList[3],
            _deviceEntity!.service4.toString(),
            infomationNameList[4],
            list[4],
            remarkList[4],
            _deviceEntity!.service5.toString(),
          ),
          const SizedBox(
            height: 10,
          ),
          _getDialogContentView(
              infomationNameList[5],
              list[5],
              remarkList[5],
              _deviceEntity!.service6.toString(),
              infomationNameList[6],
              list[6],
              remarkList[6],
              _deviceEntity!.service7.toString(),
              infomationNameList[7],
              list[7],
              remarkList[7],
              _deviceEntity!.service8.toString(),
              infomationNameList[8],
              list[8],
              remarkList[8],
              _deviceEntity!.service9.toString(),
              infomationNameList[9],
              list[9],
              remarkList[9],
              _deviceEntity!.service10.toString()),
        ],
      ),
    );
  }
  //绘制检修dialog界面
  Widget _getDialogContentView(
      String name1,
      String info1,
      String remark1,
      String day1,
      String name2,
      String info2,
      String remark2,
      String day2,
      String name3,
      String info3,
      String remark3,
      String day3,
      String name4,
      String info4,
      String remark4,
      String day4,
      String name5,
      String info5,
      String remark5,
      String day5) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const SizedBox(
          width: 16,
        ),
        _getItemDialogView(name1, remark1, day1, info1),
        const SizedBox(
          width: 5,
        ),
        _getItemDialogView(name2, remark2, day2, info2),
        const SizedBox(
          width: 5,
        ),
        _getItemDialogView(name3, remark3, day3, info3),
        const SizedBox(
          width: 5,
        ),
        _getItemDialogView(name4, remark4, day4, info4),
        const SizedBox(
          width: 5,
        ),
        _getItemDialogView(name5, remark5, day5, info5),
        const SizedBox(
          width: 16,
        )
      ],
    );
  }
  //检修信息每个item
  Widget _getItemDialogView(
      String name, String remark, String day, String info) {
    return Expanded(
        child: InkWell(
      onTap: () {
        Get.back();
        EasyLoading.showToast(
            '检修设备信息\n设备名称:$name：$remark\n检修周期：$day天\n剩余时间：$info天',
            toastPosition: EasyLoadingToastPosition.bottom);
      },
      child: Column(
        children: [
          Text(name),
          const SizedBox(
            height: 5,
          ),
          Text(info)
        ],
      ),
    ));
  }

/**
 * ("功率")  "kW";
("频率") "Hz";
("电流")) "A";
("电压"))"V";
("水压"))"kPa";
("温度"))"℃";
 */
  String getUnitText(String name) {
    if (name.contains('功率')) {
      return 'kW';
    } else if (name.contains('频率')) {
      return 'Hz';
    } else if (name.contains('电流')) {
      return 'A';
    } else if (name.contains('电压')) {
      return 'V';
    } else if (name.contains('水压')) {
      return 'kPa';
    } else if (name.contains('温度')) {
      return '℃';
    } else {
      return '';
    }
  }
}
